# coding:utf8

# 查询车辆
import base64
import codecs
import json
import pickle
import re
import sys
import traceback
import urllib

import jsonpath
import time
from bs4 import BeautifulSoup

from common import config
from common.MqSend import send_mq
from common.dama.damaUtil import dama
from common.log import Logger

from common.redisUtil import CRedis
from my_dbUtil.dbInsert import soupDb
from request_ancheng.get_use_year import get_user_years, codeMap, PHCC_VHL_USEYEAR_MAP, JQ_PHCC_VHL_USEYEAR_MAP

from request_ancheng.login import login_ancheng
from request_ancheng.request_body import _damage_insurance_namt_20, _third_party_insurance_15, \
    _driver_liability_insurance_13, _pass_liability_insurance_14, _theft_insurance_namt_18, \
    _autoignition_insurance_namt_5, _crush_insurance_namt_8, _wade_insurance_namt_10, _scratch_insurance_namt_19
from request_ancheng.request_data import query_car, get_car_id, get_car_info, get_premium_data, get_vehcle_code, \
    query_car_model
from request_ancheng.template import get_dw
from request_cic import utils
from request_cic.CicredisBodyRequest import get_redis_body
from request_cic.feebody2 import compare_date
from request_epicc.utils import pic2Str
from request_pingan.utils import compare_time40, conver_timestamp

reload(sys)
sys.setdefaultencoding('utf-8')

log = Logger()


# 获取协商价格
def get_Vhl_NNewPurchaseValue(insrncBgnTm, fstRegTm, nMonDespRate, NResvNum2):
    months = int(insrncBgnTm[:4]) - int(fstRegTm[:4])
    months *= 12
    months += (int(insrncBgnTm[5:7]) - int(fstRegTm[5:7]))

    if int(fstRegTm[8:10]) > int(insrncBgnTm[8:10]):
        months -= 1

    Vhl_NNewPurchaseValue = int(NResvNum2) * (1 - int(months) * float(nMonDespRate))

    Vhl_NNewPurchaseValue = round(Vhl_NNewPurchaseValue, 2)

    return Vhl_NNewPurchaseValue


# 根据车牌号和车架号获取PLAT_ID
def get_car(session, CPlateNo, searchVin):
    ret = get_car_id(session, CPlateNo, searchVin)

    response_body = json.loads(ret.content)

    id = response_body["RESULT_MSG"]

    PLAT_ID = id[:30]
    code = id[36:]
    # YZM_CODE = pic2Str(base64.b64decode(code))
    YZM_CODE = dama("3", code)  # 老王打码
    ret = get_car_info(session, PLAT_ID, YZM_CODE)

    return ret


# 总请求
def get_premium_request(session, endDate, CPlateNo, searchVin, insuranceType, car_info, PrmCoef_NExpectTotal='0'):
    Applicant_CAppNme = car_info.get('Applicant_CAppNme', '')
    seats = car_info.get('seats', '')
    Vhl_CEngNo = car_info.get('Vhl_CEngNo', '')
    Vhl_CFstRegYm = car_info.get('Vhl_CFstRegYm', '')
    Vhl_CRegVhlTyp = car_info.get('Vhl_CRegVhlTyp', '')
    Vhl_CProdPlace = car_info.get('Vhl_CProdPlace', '')
    Vhl_CBrandNme = car_info.get('Vhl_CBrandNme', '')
    VEHICLE_REGISTER_DATE = car_info.get('VEHICLE_REGISTER_DATE', '')
    Vhl_NResvNum2 = car_info.get('Vhl_NResvNum2', '')
    Vehcle_Code = car_info.get('Vehcle_Code', '')
    Cmodel_Code = car_info.get('Cmodel_Code', '')
    Vhl_NDisplacement = car_info.get('Vhl_NDisplacement', '')
    VsTax_NCurbWt = car_info.get('VsTax_NCurbWt', '')

    # 查询保费
    SY_Vhl_CMonDespRate = "0.006"  # 折旧率（固定）
    Vhl_NNewPurchaseValue = get_Vhl_NNewPurchaseValue(endDate, Vhl_CFstRegYm, SY_Vhl_CMonDespRate, Vhl_NResvNum2)
    log.info('保额 - {0}'.format(Vhl_NNewPurchaseValue))

    Vhl_CPlateTyp = '02'  # 种类
    Applicant_CAppNme = Applicant_CAppNme
    Applicant_CCertfCls = "123007"
    Applicant_CCertfCde = "510130197608144113"
    Applicant_CResvTxt12 = "1"
    Applicant_CClntAddr = "中国四川省成都市成华区保和乡东升村10组29号附1号"
    Applicant_CMobile = "13981876776"

    Insured_CInsuredNme = Applicant_CAppNme
    Insured_CCertfCls = Applicant_CCertfCls
    Insured_CCertfCde = Applicant_CCertfCde
    Insured_CResvTxt12 = Applicant_CResvTxt12
    Insured_CClntAddr = Applicant_CClntAddr
    Insured_CMobile = Applicant_CMobile

    Vhlowner_COwnerNme = Applicant_CAppNme
    Vhlowner_CCertfCls = Applicant_CCertfCls
    Vhlowner_CCertfCde = Applicant_CCertfCde

    Base_TAppTm = utils.getlatedate(0)  # （计算）投保日期
    Base_TIssueTm = utils.getlatedate(0)  # 签单日期

    if endDate != "":
        # 保险结束时间与当前时间比较
        datestr = compare_date(endDate, utils.getlatedate(0))
        TLastSaliEndDate = ""
        SY_Base_TInsrncBgnTm = utils.getlatedate(1, datestr) + ' 00:00:00'  # 保险起止期(商)
        SY_Base_TInsrncEndTm = utils.getlatedate(365, datestr) + " 23:59:59"  # 保险起止期(商)
        JQ_Base_TInsrncBgnTm = utils.getlatedate(1, datestr) + " 00:00:00"  # 保险起止期(交)
        JQ_Base_TInsrncEndTm = utils.getlatedate(365, datestr) + " 23:59:59"  # 保险起止期(交)
    else:
        TLastSaliEndDate = utils.getlatedate(0)  ##当前日期
        SY_Base_TInsrncBgnTm = utils.getlatedate(1) + ' 00:00:00'  # 保险起止期(商)
        SY_Base_TInsrncEndTm = utils.getlatedate(365) + " 23:59:59"  # 保险起止期(商)
        JQ_Base_TInsrncBgnTm = utils.getlatedate(1) + " 00:00:00"  # 保险起止期(交)
        JQ_Base_TInsrncEndTm = utils.getlatedate(365) + " 23:59:59"  # 保险起止期(交)

    Base_CAreaFlag = "320100"  # 地区标识（固定）
    Base_CCountyCde = "320104"  # 保单归属地（固定）
    Base_CVhlchanlFlag = "0"  # 车型渠道（固定）
    Base_CDisptSttlCde = "007001"  # 争议处理（固定）
    Base_CFinTyp = "002001"  # 缴费方式（固定）
    Base_CBsnsTyp = "19002"  # 业务来源（固定）
    Base_CChaType = "191008"  # 渠道中级（固定）
    Base_CChaSubtype = "19100801"  # 渠道子类（固定）
    Base_CSlsId = "132021610"  # 渠道维护员工号（固定）
    Base_CSlsNme = "田江平"  # 渠道维护员名称（固定）
    Base_CBrkrCde = "10000001502"  # 代理人（固定）
    Base_CAgtAgrNo = "B32201700075"  # 代理协议（固定）
    Base_NSubCoNo = "0"  # 补充协议号（固定）
    Base_CAgtSls = "32020203008033"  # 中介经办人（固定）
    Base_CTel = "13771615588"  # 联系电话（固定）
    Base_CRatioTyp = "1"  # 短期费率类型（固定）
    Base_CAgriMrk = "2"  # 涉农标志（固定）

    Vhl_CNewMrk = "0"  # 是否上牌（固定）'0 是 1 否'
    Vhl_CNewVhlFlag = "0"  # 是否新车（固定）'1 是 0 否'

    SY_Vhl_CBizMrk = "345018001"  # 商 使用性质（固定）
    SY_Vhl_CUsageCde = "345019001"  # 商 车辆种类（固定）
    SY_Vhl_CVhlTyp = "345002001"  # 商 车辆种类细分

    JQ_Vhl_CBizMrk = "345009001"  # 交 使用性质（固定）
    JQ_Vhl_CUsageCde = "345010001"  # 交 车辆种类（固定）
    JQ_Vhl_CVhlTyp = "345002001"  # 交 车辆种类细分

    if int(seats) <= 6:
        SY_Vhl_CVhlTyp = "345002001"
        JQ_Vhl_CVhlTyp = "345002001"
    if int(seats) > 6 and int(seats) <= 10:
        SY_Vhl_CVhlTyp = "345002002"
        JQ_Vhl_CVhlTyp = "345002002"
    if int(seats) > 10:
        SY_Vhl_CVhlTyp = "345002003"
        JQ_Vhl_CVhlTyp = "345002003"

    Vhl_CPlateTyp = Vhl_CPlateTyp  # 号牌种类（获取）
    Vhl_CPlateNo = CPlateNo  # 车牌号
    Vhl_CFrmNo = searchVin  # 车架号
    Vhl_CEngNo = Vhl_CEngNo  # 发动机号（获取）
    Vhl_CFstRegYm = Vhl_CFstRegYm  # 初登日期（获取）
    Vhl_CRegVhlTyp = Vhl_CRegVhlTyp  # 交管车辆种类（获取）
    Vhl_NNewPurchaseValue = Vhl_NNewPurchaseValue  # 协商价值（获取）
    Vhl_CProdPlace = Vhl_CProdPlace  # 国产/进口 国产-0 进口-1 （手动输入）
    SY_Vhl_CMonDespRate = SY_Vhl_CMonDespRate  # 折旧率（计算）
    Vhl_CBrandNme = Vhl_CBrandNme  # 品牌车型（获取）
    userYear = get_user_years(endDate, VEHICLE_REGISTER_DATE)  # 商 车龄（计算获取）345020003

    SY_Vhl_CUseYear = codeMap.get(userYear, '345020004')  # 商车龄
    SY_Vhl_CAddriskVhlAge = PHCC_VHL_USEYEAR_MAP.get(userYear, '345003010')

    JQ_Vhl_CUseYear = JQ_PHCC_VHL_USEYEAR_MAP.get(userYear, '345011005')  # 交 车龄
    SY_Vhl_CEcdemicMrk = "0"  # 商是否外地车（获取）本地车-0
    JQ_Vhl_CEcdemicMrk = "0"  # 交是否外地车（获取）本地车-0
    Vhl_NSeatNum = seats  # 座位数（获取）
    Vhl_NTonage = "0.000000"  # 吨位（获取）

    SY_Vhl_CVhlTransFlag = "0"  # 商 车辆过户
    JQ_Vhl_CVhlTransFlag = "0"  # 交 车辆过户

    JQ_Vhl_CFuelType = "0"  # 交能源类型（燃油）

    Vhl_CProjCde = "A3201ZZ001"  # 项目代码 （固定）

    CDductMrk = "345021001"  # 不计免赔 是
    No_CDductMrk = "345021007"  # 不计免赔 否

    # 车船税
    VsTax_CPaytaxTyp = 'T'  # 纳税类型代码（固定）
    VsTax_CTaxdptVhltyp = '345030002'  # 行驶证车辆类型（固定）
    VsTax_TTaxEffBgnTm = time.strftime("%Y", time.localtime()) + '-01-01'  # 税款所属期始（获取）
    VsTax_TTaxEffEndTm = time.strftime("%Y", time.localtime()) + '-12-31'  # 税款所属期止（获取）
    VsTax_CTaxpayerComId = '370784197612165510'  # 纳税人识别号
    VsTax_CMotorvehFueltyp = 'A'  # 燃油种类

    _driverDutyPremium = insuranceType.get("driverDutyPremium", None)  # 驾驶人责任险 check
    _driverDutyBenchMarkPremium = CDductMrk if int(
        insuranceType.get("driverDutyBenchMarkPremium", "0")) else No_CDductMrk

    _carDamagePremium = insuranceType.get("carDamagePremium", "0")  # 车损险
    _carDamageBenchMarkPremium = CDductMrk if int(
        insuranceType.get("carDamageBenchMarkPremium", "0")) else No_CDductMrk

    _otherHurtPremium = insuranceType.get("otherHurtPremium", None)  # 机动车第三责任保险 check
    _otherHurtBenchMarkPremium = CDductMrk if int(
        insuranceType.get("otherHurtBenchMarkPremium", "0")) else No_CDductMrk

    _passengerDutyPremium = insuranceType.get("passengerDutyPremium", None)  # 乘客责任险 check
    _passengerBenchMarkPremium = CDductMrk if int(
        insuranceType.get("passengerBenchMarkPremium", "0")) else No_CDductMrk

    _carTheftPremium = insuranceType.get("carTheftPremium", "0")  # 盗抢险
    _carTheftBenchMarkPremium = CDductMrk if int(
        insuranceType.get("carTheftBenchMarkPremium", "0")) else No_CDductMrk

    _carFireBrokenBenchMarkPremium = insuranceType.get("carFirePremium", "0")  # 自燃险
    _carFireBrokenBenchMarkPremium22 = CDductMrk if int(
        insuranceType.get("carFireBrokenBenchMarkPremium", "0")) else No_CDductMrk

    _glassBrokenPremium = insuranceType.get("glassBrokenPremium", "0")  # 玻璃破碎险

    _engineWadingBenchMarkPremium = insuranceType.get("engineWadingPremium", "0")  # 涉水险
    _engineWadingBenchMarkPremium22 = CDductMrk if int(
        insuranceType.get("engineWadingBenchMarkPremium", "0")) else No_CDductMrk

    _carNickPremium = insuranceType.get("carNickPremium", None)  # 划痕险 check
    _carNickBenchMarkPremium = CDductMrk if int(insuranceType.get("carNickBenchMarkPremium", "0")) else No_CDductMrk

    # 删除车损险需删除其他险
    if not int(_carDamagePremium):
        _carFireBrokenBenchMarkPremium = '0'  # 自燃险
        _glassBrokenPremium = '0'  # 玻璃破碎险
        _carNickPremium['isCheck'] = '0'  # 划痕险
        _engineWadingBenchMarkPremium = '0'  # 涉水险

    # 根据所传的参数生成动态消息体
    damage_insurance_namt_20 = _damage_insurance_namt_20(Vhl_NNewPurchaseValue, _carDamageBenchMarkPremium,
                                                         SY_Base_TInsrncBgnTm, SY_Base_TInsrncEndTm) if int(
        _carDamagePremium) else ''  # 机动车损失保险

    third_party_insurance_15 = _third_party_insurance_15(_otherHurtPremium, _otherHurtBenchMarkPremium,
                                                         SY_Base_TInsrncBgnTm,
                                                         SY_Base_TInsrncEndTm) if _otherHurtPremium and int(
        _otherHurtPremium.get("isCheck", 0)) else ''  # 第三者责任险

    driver_liability_insurance_13 = _driver_liability_insurance_13(_driverDutyPremium, _driverDutyBenchMarkPremium,
                                                                   SY_Base_TInsrncBgnTm,
                                                                   SY_Base_TInsrncEndTm) if _driverDutyPremium and int(
        _driverDutyPremium.get("isCheck", 0)) else ''  # 驾驶人责任险

    pass_liability_insurance_14 = _pass_liability_insurance_14(_passengerDutyPremium, seats,
                                                               _passengerBenchMarkPremium, SY_Base_TInsrncBgnTm,
                                                               SY_Base_TInsrncEndTm) if _passengerDutyPremium and int(
        _passengerDutyPremium.get("isCheck", 0)) else ''  # 乘客责任险

    theft_insurance_namt_18 = _theft_insurance_namt_18(Vhl_NNewPurchaseValue, _carTheftBenchMarkPremium,
                                                       SY_Base_TInsrncBgnTm, SY_Base_TInsrncEndTm) if int(
        _carTheftPremium) else ''  # 盗抢险

    autoignition_insurance_namt_5 = _autoignition_insurance_namt_5(Vhl_NNewPurchaseValue,
                                                                   _carFireBrokenBenchMarkPremium22,
                                                                   SY_Base_TInsrncBgnTm,
                                                                   SY_Base_TInsrncEndTm) if int(
        _carFireBrokenBenchMarkPremium) else ''  # 自燃险

    crush_insurance_namt_8 = _crush_insurance_namt_8(Vhl_NResvNum2, SY_Base_TInsrncBgnTm,
                                                     SY_Base_TInsrncEndTm) if int(
        _glassBrokenPremium) else ''  # 玻璃破碎险险

    wade_insurance_namt_10 = _wade_insurance_namt_10(Vhl_NNewPurchaseValue, _engineWadingBenchMarkPremium22,
                                                     SY_Base_TInsrncBgnTm, SY_Base_TInsrncEndTm) if int(
        _engineWadingBenchMarkPremium) else ''  # 涉水险

    scratch_insurance_namt_19 = _scratch_insurance_namt_19(_carNickPremium, _carNickBenchMarkPremium,
                                                           SY_Base_TInsrncBgnTm,
                                                           SY_Base_TInsrncEndTm) if _carNickPremium and int(
        _carNickPremium.get("isCheck", 0)) else ''  # 划痕险

    DW_DATA = get_dw(
        Applicant_CAppNme, Applicant_CCertfCls, Applicant_CCertfCde, Applicant_CResvTxt12, Applicant_CClntAddr,
        Applicant_CMobile, Insured_CInsuredNme, Insured_CCertfCls, Insured_CCertfCde, Insured_CResvTxt12,
        Insured_CClntAddr, Insured_CMobile, Vhlowner_COwnerNme, Vhlowner_CCertfCls, Vhlowner_CCertfCde, Base_TAppTm,
        SY_Base_TInsrncBgnTm, SY_Base_TInsrncEndTm, JQ_Base_TInsrncBgnTm, JQ_Base_TInsrncEndTm, Base_CAreaFlag,
        Base_CCountyCde, Base_CVhlchanlFlag, Base_CDisptSttlCde, Base_CFinTyp, Base_CBsnsTyp, Base_CChaType,
        Base_CChaSubtype, Base_CSlsId, Base_CSlsNme, Base_CBrkrCde, Base_CAgtAgrNo, Base_NSubCoNo, Base_CAgtSls,
        Base_CTel, Base_CRatioTyp, Base_CAgriMrk, SY_Vhl_CBizMrk, SY_Vhl_CUsageCde, SY_Vhl_CVhlTyp, JQ_Vhl_CBizMrk,
        JQ_Vhl_CUsageCde, JQ_Vhl_CVhlTyp, Vhl_CPlateTyp, Vhl_CPlateNo, Vhl_CFrmNo, Vhl_CEngNo, Vhl_CFstRegYm,
        Vhl_CRegVhlTyp, Vhl_NNewPurchaseValue, Vhl_CProdPlace, SY_Vhl_CMonDespRate, Vhl_CBrandNme, SY_Vhl_CUseYear,
        JQ_Vhl_CUseYear, SY_Vhl_CEcdemicMrk, JQ_Vhl_CEcdemicMrk, Vhl_NSeatNum, Vhl_NTonage, JQ_Vhl_CFuelType,
        Base_TIssueTm, Vhl_CNewMrk, Vhl_CNewVhlFlag, SY_Vhl_CVhlTransFlag, Vhl_CProjCde,
        damage_insurance_namt_20, third_party_insurance_15, driver_liability_insurance_13,
        pass_liability_insurance_14, theft_insurance_namt_18, autoignition_insurance_namt_5, crush_insurance_namt_8,
        wade_insurance_namt_10, scratch_insurance_namt_19, Vehcle_Code, Cmodel_Code, SY_Vhl_CAddriskVhlAge,
        Vhl_NResvNum2, JQ_Vhl_CVhlTransFlag, VsTax_CPaytaxTyp, VsTax_CTaxdptVhltyp, VsTax_TTaxEffBgnTm,
        VsTax_TTaxEffEndTm, VsTax_CTaxpayerComId, VsTax_CMotorvehFueltyp, Vhl_NDisplacement, PrmCoef_NExpectTotal,
        VsTax_NCurbWt)

    DW_DATA = urllib.quote(urllib.quote(str(DW_DATA)))

    data = "ADAPTER_TYPE=JSON_TYPE&SERVICE_TYPE=ACTION_SERVIC&CODE_TYPE=CODE_TYPE&BEAN_HANDLE=baseAction&ACTION_HANDLE=perform&SERVICE_NAME=quickAppBaseBizAction&SERVICE_MOTHOD=calcPremium&DW_DATA={DW_DATA}&HELPCONTROLMETHOD=common&SCENE=UNDEFINED&BIZ_SYNCH_CONTINUE=false&CUST_DATA=%3A0336%3APLY_APP_NEW_SCENE".format(
        DW_DATA=DW_DATA)

    ret = get_premium_data(session, data)

    return ret


def query_car_info(session, data, endDate, CPlateNo, searchVin):
    # 查询车辆
    try:
        ret = query_car(session, CPlateNo, searchVin)

        if '车辆识别失败' in ret.text or not ret.text:

            # 交管车型查询
            try:
                result = None
                for i in range(5):
                    result = get_car(session, CPlateNo, searchVin)
                    if not '录入的校验码有误' in result.text:
                        break
                    if i == 4 and '录入的校验码有误' in result.text:
                        log.info('验证码5次识别失败')
                        return 0

                if '交管车辆查询校验信息不存在' in result.text:
                    log.info('{0},{1} - 交管车辆查询校验信息不存在'.format(CPlateNo, searchVin))
                    return 0

                ra = "DATA:\['(.*?)'\]"
                rb = re.compile(ra)

                title_list = re.findall(rb, result.text)
                html = title_list[0]
                soup = BeautifulSoup(html, 'html.parser')
                a = soup.find('dataobj', attrs={"status": "UNCHANGED"})
                soup = BeautifulSoup(str(a), 'html.parser')
            except Exception as e:
                log.error(e)
                log.error(traceback.format_exc())
                return 0

            VEHICLE_MODEL = soup.find("attribute", attrs={"name": "VEHICLE_MODEL"}).get_text()  # 车辆型号

            VEHICLE_MODEL = VEHICLE_MODEL[:-1] + VEHICLE_MODEL[-1:].lower()

            ret = query_car_model(session, VEHICLE_MODEL)

            if '车辆识别失败' in ret.text or not ret.text:
                log.info('{0},{1} - 车辆识别失败'.format(CPlateNo, searchVin))
                return 0

        ra = "DATA:\['(.*?)'\]"
        rb = re.compile(ra)

        title_list = re.findall(rb, ret.text)
        if not title_list:
            session = login_ancheng()
            return get_premium(session, data)

        html = title_list[0]
        soup = BeautifulSoup(html, 'html.parser')
        a = soup.find_all('dataobj', attrs={"status": "UNCHANGED"})
        a = list(a)

        c = sorted(a, key=lambda x: int(
            BeautifulSoup(str(x), 'html.parser').find("attribute", attrs={"name": "VehiclePrice"}).get_text()),
                   reverse=False)
        d = c[0]
        car_value = int(
            BeautifulSoup(str(d), 'html.parser').find("attribute", attrs={"name": "VehiclePrice"}).get_text())
        log.info('车辆价格 - {0}'.format(car_value))

        soup = BeautifulSoup(str(d), 'html.parser')
    except Exception as e:
        log.error(e)
        log.error(traceback.format_exc())
        return 0

    Vhl_CBrandNme = soup.find("attribute", attrs={"name": "BrandName"}).get_text()  # 品牌
    Cmodel_Code = soup.find("attribute", attrs={"name": "VehicleId"}).get_text()[:10]  # PK

    log.info('车型编码 - {0}'.format(Cmodel_Code))

    Vhl_NResvNum2 = soup.find("attribute", attrs={"name": "VehiclePrice"}).get_text()  # 车辆价格
    Vhl_CProdPlace = soup.find("attribute", attrs={"name": "VehicleType"}).get_text()  # 种类

    # seat = int(soup.find("attribute", attrs={"name": "VehicleSeat"}).get_text())  # 座位数

    Vhl_CProdPlace = "0" if Vhl_CProdPlace == "国产" else "1"

    try:
        ret = get_vehcle_code(session, Cmodel_Code)

        ra = "###(.+?)###"
        rb = re.compile(ra)

        Vehcle_Code = re.findall(rb, ret.text)[0]

        if Vehcle_Code == 'null':
            log.info('无法获取行业车型编码')
            return 0

    except Exception as e:
        log.error(e)
        log.error(traceback.format_exc())
        return 0

    # 交管车型查询
    try:
        result = None
        for i in range(5):
            result = get_car(session, CPlateNo, searchVin)
            if not '录入的校验码有误' in result.text:
                break
            if i == 4 and '录入的校验码有误' in result.text:
                log.info('验证码5次识别失败')
                return 0

        if '交管车辆查询校验信息不存在' in result.text:
            log.info('{0},{1} - 交管车辆查询校验信息不存在'.format(CPlateNo, searchVin))
            return 0

        ra = "DATA:\['(.*?)'\]"
        rb = re.compile(ra)

        title_list = re.findall(rb, result.text)
        html = title_list[0]
        soup = BeautifulSoup(html, 'html.parser')
        a = soup.find('dataobj', attrs={"status": "UNCHANGED"})
        soup = BeautifulSoup(str(a), 'html.parser')
    except Exception as e:
        log.error(e)
        log.error(traceback.format_exc())
        return 0

    Applicant_CAppNme = soup.find("attribute", attrs={"name": "OWNER"}).get_text()  # 车主
    Vhl_CFstRegYm = soup.find("attribute", attrs={"name": "VEHICLE_REGISTER_DATE"}).get_text()  # 初登日期
    Vhl_CRegVhlTyp = soup.find("attribute", attrs={"name": "VEHICLE_STYLE"}).get_text()  # 交管车辆种类
    LIMIT_LOAD_PERSON = soup.find("attribute", attrs={"name": "LIMIT_LOAD_PERSON"}).get_text()  # 座位数
    DISPLACEMENT = soup.find("attribute", attrs={"name": "DISPLACEMENT"}).get_text()  # 排量
    DISPLACEMENT = float(DISPLACEMENT) / 1000

    Vhl_NDisplacement = str(DISPLACEMENT)  # 排量

    WHOLE_WEIGHT = float(soup.find("attribute", attrs={"name": "WHOLE_WEIGHT"}).get_text())
    WHOLE_WEIGHT = float(WHOLE_WEIGHT) / 1000

    VsTax_NCurbWt = str(WHOLE_WEIGHT)  # 整备质量

    seats = int(LIMIT_LOAD_PERSON)

    Vhl_CFstRegYm = Vhl_CFstRegYm[:4] + '-' + Vhl_CFstRegYm[4:6] + '-' + Vhl_CFstRegYm[6:]
    Vhl_CEngNo = soup.find("attribute", attrs={"name": "ENGINE_NO"}).get_text()  # 发动机号

    _VEHICLE_REGISTER_DATE = soup.find("attribute", attrs={"name": "VEHICLE_REGISTER_DATE"}).get_text()  # 车辆注册时间
    VEHICLE_REGISTER_DATE = _VEHICLE_REGISTER_DATE[:4] + '-' + _VEHICLE_REGISTER_DATE[
                                                               4:6] + '-' + _VEHICLE_REGISTER_DATE[6:]

    # 计算保额
    SY_Vhl_CMonDespRate = "0.006"  # 折旧率（固定）

    Vhl_NNewPurchaseValue = get_Vhl_NNewPurchaseValue(endDate, Vhl_CFstRegYm, SY_Vhl_CMonDespRate, Vhl_NResvNum2)
    #
    # log.info('保额 - {0}'.format(Vhl_NNewPurchaseValue))

    car_info = {}

    car_info['Vhl_CBrandNme'] = Vhl_CBrandNme
    car_info['Vhl_NResvNum2'] = Vhl_NResvNum2
    car_info['Vhl_CProdPlace'] = Vhl_CProdPlace
    car_info['Applicant_CAppNme'] = Applicant_CAppNme
    car_info['Vhl_CFstRegYm'] = Vhl_CFstRegYm
    car_info['Vhl_CRegVhlTyp'] = Vhl_CRegVhlTyp
    car_info['seats'] = seats
    car_info['Vhl_CEngNo'] = Vhl_CEngNo
    car_info['VEHICLE_REGISTER_DATE'] = VEHICLE_REGISTER_DATE
    car_info['Vehcle_Code'] = Vehcle_Code
    car_info['Cmodel_Code'] = Cmodel_Code
    car_info['Vhl_NNewPurchaseValue'] = Vhl_NNewPurchaseValue
    car_info['Vhl_NDisplacement'] = Vhl_NDisplacement
    car_info['VsTax_NCurbWt'] = VsTax_NCurbWt

    r = CRedis()
    r.set_vin(searchVin, "12", json.dumps(car_info, ensure_ascii=False))

    return car_info


def get_premium(session, data):
    if not session:
        session = login_ancheng()

    if not session:
        log.info(u'安诚登录失败')
        return

    searchVin = data['vinNo']
    insureCarId = data['insureCarId']
    isPhone = data['isPhone']
    sessionId = data['sessionId']
    client = data['client']
    CPlateNo = data['plateNumber']

    insuranceType = data.get("insuranceType", {})
    insuranceType_list = []
    if isinstance(insuranceType, list):
        insuranceType_list = insuranceType
    else:
        insuranceType_list.append(insuranceType)

    insuranceTypeGroupId = insuranceType_list[0].get("insuranceTypeGroupId", "")
    insuranceTypeGroup = insuranceType_list[0].get("insuranceTypeGroup", "")

    try:
        endDate = data.get("endDate", "")
        # endDate = "2017-04-07"
        if endDate != "":
            min_time = compare_time40(endDate)
            if min_time > config.days:
                log.error("安诚保险查询在40天内的 车牌号为 %s 保险结束时间为 %s" % (CPlateNo, endDate))
                send_mq(client, CPlateNo, "安诚保险查询在40天内的 车牌号为 %s 保险结束时间为 %s" % (CPlateNo, endDate), "2", "12",
                        sessionId, isPhone, insuranceTypeGroupId, insuranceTypeGroup)
                return "安诚保险查询在40天内的 车牌号为 %s 保险结束时间为 %s" % (CPlateNo, endDate)
            if min_time < 0:
                endDate = utils.getlatedate(1)
        else:
            endDate = utils.getlatedate(1)

        # 查询redis中是否有信息
        r = CRedis()
        car_info = r.get_vin(searchVin, "12")

        if not car_info:
            car_info = query_car_info(session, data, endDate, CPlateNo, searchVin)
        else:
            car_info = eval(car_info)

        if not car_info:
            log.error('查询车辆信息失败')
            send_mq(client, CPlateNo, "查询车辆信息失败", "2", "12", sessionId, isPhone,
                    insuranceTypeGroupId, insuranceTypeGroup)
            return

        for insuranceType in insuranceType_list:

            ret = get_premium_request(session, endDate, CPlateNo, searchVin, insuranceType, car_info)

            try:
                if '重复投保' in json.dumps(ret.json(), ensure_ascii=False):
                    log.info('重复投保，重新获取终保日期')

                    ra = "\d{4}-\d{2}-\d{2}"
                    rb = re.compile(ra)

                    rc = re.findall(rb, ret.content)
                    if rc and 'null' not in rc:

                        if len(rc) == 2:
                            end_date = rc[1] if rc[1] > rc[0] else rc[0]
                        else:
                            end_date = rc[0]

                        log.info('终保日期 - {0}'.format(end_date))

                        min_time = compare_time40(end_date)
                        if min_time > config.days:
                            log.error("安诚保险查询在40天内的 车牌号为 %s 保险结束时间为 %s" % (CPlateNo, end_date))
                            send_mq(client, CPlateNo, "安诚保险查询在40天内的 车牌号为 %s 保险结束时间为 %s" % (CPlateNo, end_date), "2",
                                    "12", sessionId, isPhone, insuranceTypeGroupId, insuranceTypeGroup)
                            return "安诚保险查询在40天内的 车牌号为 %s 保险结束时间为 %s" % (CPlateNo, end_date)

                        endtime = conver_timestamp(end_date + " 23:59:59")
                        currnt_time = int(time.time())

                        if endtime < currnt_time:
                            endDate = utils.getlatedate(1)
                        else:
                            endDate = end_date

                        car_info['endDate'] = endDate
                        # 当是重复投保，取endDate重新发送获取保费请求
                        ret = get_premium_request(session, endDate, CPlateNo, searchVin, insuranceType, car_info)

                        if '重复投保' in json.dumps(ret.json(), ensure_ascii=False):
                            log.info('重复投保，获取终保日期还是重复投保')
                            send_mq(client, CPlateNo, "重复投保，获取终保日期还是重复投保", "2", "12", sessionId, isPhone,
                                    insuranceTypeGroupId, insuranceTypeGroup)
                            return

                    else:
                        log.info('重复投保，无法获取终保日期，程序结束')
                        send_mq(client, CPlateNo, "重复投保，无法获取终保日期", "2", "12", sessionId, isPhone, insuranceTypeGroupId,
                                insuranceTypeGroup)
                        return

                log.info('endDate - {0}'.format(endDate))

                if len(ret.json()['WEB_DATA']) > 0:
                    response_body_1 = json.loads(ret.text)
                    PrmCoef_DW = \
                        jsonpath.jsonpath(response_body_1, "$.WEB_DATA[?(@.dwName=='prodDef.vhl.PrmCoef_DW')]")[0]
                    PrmCoef_DW_dataObjVoList = jsonpath.jsonpath(PrmCoef_DW, "$.dataObjVoList")
                    PrmCoef_DW_dict = PrmCoef_DW_dataObjVoList[0][0]['attributeVoList']

                    SY_PrmCoef_NResvNum1 = float(PrmCoef_DW_dict["SY_PrmCoef.NResvNum1"]["value"])  # 无忧赔款优待系数

                    PrmCoef_NTrafficVi = float(PrmCoef_DW_dict["PrmCoef.NTrafficVi"]["value"])  # 交通违法调整系数

                    PrmCoef_NExpectTotal = float(SY_PrmCoef_NResvNum1) * float(
                        PrmCoef_NTrafficVi) * 0.85 * 0.85  # 整单期望折扣

                    # 带上整单期望折扣重新发送请求
                    ret = get_premium_request(session, endDate, CPlateNo, searchVin, insuranceType, car_info,
                                              PrmCoef_NExpectTotal=str(PrmCoef_NExpectTotal))

                    if len(ret.json()['WEB_DATA']) > 0:

                        response_body_2 = json.loads(ret.text)

                        PrmCoef_DW = \
                            jsonpath.jsonpath(response_body_2, "$.WEB_DATA[?(@.dwName=='prodDef.vhl.PrmCoef_DW')]")[0]
                        PrmCoef_DW_dataObjVoList = jsonpath.jsonpath(PrmCoef_DW, "$.dataObjVoList")
                        PrmCoef_DW_dict = PrmCoef_DW_dataObjVoList[0][0]['attributeVoList']

                        # 获取商业险系数
                        ratio = float(PrmCoef_DW_dict["SY_PrmCoef.NTotDisc"]["value"])  # 商业险系数
                        jq_ratio = float(PrmCoef_DW_dict["JQ_PrmCoef.NTotDisc"]["value"]) / 100  # 交强险系数

                        VsTax_DW = \
                            jsonpath.jsonpath(response_body_2, "$.WEB_DATA[?(@.dwName=='prodDef.vhl.VsTax_DW')]")[0]
                        VsTax_DW_dataObjVoList = jsonpath.jsonpath(VsTax_DW, "$.dataObjVoList")
                        VsTax_DW_dict = VsTax_DW_dataObjVoList[0][0]['attributeVoList']

                        VsTax_NAggTax = float(VsTax_DW_dict["VsTax.NAggTax"]["value"])  # 车船税
                        log.info('车船税 - {0}'.format(VsTax_NAggTax))

                        Cvrg_DW = jsonpath.jsonpath(response_body_2, "$.WEB_DATA[?(@.dwName=='prodDef.vhl.Cvrg_DW')]")[
                            0]
                        Cvrg_DW_dataObjVoList = jsonpath.jsonpath(Cvrg_DW, "$.dataObjVoList")

                        attrs = Cvrg_DW_dataObjVoList[0]

                    else:
                        msg = ret.json()['RESULT_MSG'].replace("\n", "")

                        if '期望折扣' in msg:
                            ra = "[0-9]*\.?[0-9]+"
                            rb = re.compile(ra)

                            msg_list = re.findall(rb, msg)

                            PrmCoef_NExpectTotal = float(msg_list[0])
                            # 返回期望折扣错误重新发送请求
                            ret = get_premium_request(session, endDate, CPlateNo, searchVin, insuranceType, car_info,
                                                      PrmCoef_NExpectTotal=str(PrmCoef_NExpectTotal))

                            if len(ret.json()['WEB_DATA']) > 0:
                                response_body_2 = json.loads(ret.text)

                                PrmCoef_DW = \
                                    jsonpath.jsonpath(response_body_2,
                                                      "$.WEB_DATA[?(@.dwName=='prodDef.vhl.PrmCoef_DW')]")[0]
                                PrmCoef_DW_dataObjVoList = jsonpath.jsonpath(PrmCoef_DW, "$.dataObjVoList")
                                PrmCoef_DW_dict = PrmCoef_DW_dataObjVoList[0][0]['attributeVoList']

                                # 获取商业险系数
                                ratio = float(PrmCoef_DW_dict["SY_PrmCoef.NTotDisc"]["value"])  # 商业险系数
                                jq_ratio = float(PrmCoef_DW_dict["JQ_PrmCoef.NTotDisc"]["value"]) / 100  # 交强险系数

                                VsTax_DW = \
                                    jsonpath.jsonpath(response_body_2,
                                                      "$.WEB_DATA[?(@.dwName=='prodDef.vhl.VsTax_DW')]")[0]
                                VsTax_DW_dataObjVoList = jsonpath.jsonpath(VsTax_DW, "$.dataObjVoList")
                                VsTax_DW_dict = VsTax_DW_dataObjVoList[0][0]['attributeVoList']

                                VsTax_NAggTax = float(VsTax_DW_dict["VsTax.NAggTax"]["value"])  # 车船税
                                log.info('车船税 - {0}'.format(VsTax_NAggTax))

                                Cvrg_DW = \
                                    jsonpath.jsonpath(response_body_2,
                                                      "$.WEB_DATA[?(@.dwName=='prodDef.vhl.Cvrg_DW')]")[
                                        0]
                                Cvrg_DW_dataObjVoList = jsonpath.jsonpath(Cvrg_DW, "$.dataObjVoList")

                                attrs = Cvrg_DW_dataObjVoList[0]

                            else:
                                msg = ret.json()['RESULT_MSG'].replace("\n", "")
                                log.error(msg)
                                send_mq(client, CPlateNo, msg, "2", "12", sessionId, isPhone, insuranceTypeGroupId,
                                        insuranceTypeGroup)
                                return

                        else:
                            log.error(msg)
                            send_mq(client, CPlateNo, msg, "2", "12", sessionId, isPhone, insuranceTypeGroupId,
                                    insuranceTypeGroup)
                            return
                else:
                    msg = ret.json()['RESULT_MSG'].replace("\n", "")
                    log.error(msg)
                    send_mq(client, CPlateNo, msg, "2", "12", sessionId, isPhone, insuranceTypeGroupId,
                            insuranceTypeGroup)
                    return

            except Exception as e:
                log.error(e)
                log.error(traceback.format_exc())
                send_mq(client, CPlateNo, "未知异常", "2", "12", sessionId, isPhone, insuranceTypeGroupId,
                        insuranceTypeGroup)
                return

            Premium = {}
            MarkPremium = {}
            total_money = 0

            for i, k in enumerate(attrs):
                num = int(k["attributeVoList"]["Cvrg.NSeqNo"]["value"])
                if num == 15:
                    otherHurtPremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]["value"]) * ratio  # 三者险
                    total_money += otherHurtPremium
                    # log.info(str(otherHurtPremium) + u' 三者险')
                    Premium['otherHurtPremium'] = round(otherHurtPremium, 2)

                    otherHurtBenchMarkPremium = otherHurtPremium * 0.15  # 三者险不计免赔
                    MarkPremium['otherHurtBenchMarkPremium'] = round(otherHurtBenchMarkPremium, 2)

                elif num == 20:
                    carDamagePremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]["value"]) * ratio  # 车损险
                    total_money += carDamagePremium
                    # log.info(str(carDamagePremium) + u' 车损险')
                    Premium['carDamagePremium'] = round(carDamagePremium, 2)

                    carDamageBenchMarkPremium = carDamagePremium * 0.15  # 车损险不计免赔
                    MarkPremium['carDamageBenchMarkPremium'] = round(carDamageBenchMarkPremium, 2)

                elif num == 13:
                    driverDutyPremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]["value"]) * ratio  # 车上人员险（司机）
                    total_money += driverDutyPremium
                    # log.info(str(driverDutyPremium) + u' 车上人员险（司机）')
                    Premium['driverDutyPremium'] = round(driverDutyPremium, 2)

                    driverDutyBenchMarkPremium = driverDutyPremium * 0.15  # 车上人员险（司机）不计免赔
                    MarkPremium['driverDutyBenchMarkPremium'] = round(driverDutyBenchMarkPremium, 2)

                elif num == 14:
                    passengerDutyPremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]["value"]) * ratio  # 车上人员险（乘客）
                    total_money += passengerDutyPremium
                    # log.info(str(passengerDutyPremium) + u' 车上人员险（乘客）')
                    Premium['passengerDutyPremium'] = round(passengerDutyPremium, 2)

                    passengerBenchMarkPremium = passengerDutyPremium * 0.15  # 车上人员险（乘客）不计免赔
                    MarkPremium['passengerBenchMarkPremium'] = round(passengerBenchMarkPremium, 2)

                elif num == 18:
                    carTheftPremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]["value"]) * ratio  # 盗抢险
                    total_money += carTheftPremium
                    # log.info(str(carTheftPremium) + u' 盗抢险')
                    Premium['carTheftPremium'] = round(carTheftPremium, 2)

                    carTheftBenchMarkPremium = carTheftPremium * 0.20  # 盗抢险不计免赔
                    MarkPremium['carTheftBenchMarkPremium'] = round(carTheftBenchMarkPremium, 2)

                elif num == 19:
                    carNickPremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]["value"]) * ratio  # 划痕险
                    total_money += carNickPremium
                    # log.info(str(carNickPremium) + u' 划痕险')
                    Premium['carNickPremium'] = round(carNickPremium, 2)

                    carNickBenchMarkPremium = carNickPremium * 0.15  # 划痕险不计免赔
                    MarkPremium['carNickBenchMarkPremium'] = round(carNickBenchMarkPremium, 2)

                elif num == 8:
                    glassBrokenPremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]["value"]) * ratio  # 玻璃破碎险
                    total_money += glassBrokenPremium
                    # log.info(str(glassBrokenPremium) + u' 玻璃破碎险')
                    Premium['glassBrokenPremium'] = round(glassBrokenPremium, 2)

                    glassBrokenMarkPremium = glassBrokenPremium * 0.20  # 玻璃破碎险不计免赔
                    MarkPremium['glassBrokenMarkPremium'] = round(glassBrokenMarkPremium, 2)

                elif num == 5:
                    carFirePremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]["value"]) * ratio  # 自燃险
                    total_money += carFirePremium
                    # log.info(str(carFirePremium) + u' 自燃险')
                    Premium['carFirePremium'] = round(carFirePremium, 2)

                    carFireMarkPremium = carFirePremium * 0.20  # 自燃险不计免赔
                    MarkPremium['carFireMarkPremium'] = round(carFireMarkPremium, 2)

                elif num == 10:
                    engineWadingPremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]["value"]) * ratio  # 涉水险
                    total_money += engineWadingPremium
                    # log.info(str(engineWadingPremium) + u' 涉水险')
                    Premium['engineWadingPremium'] = round(engineWadingPremium, 2)

                    engineWadingMarkPremium = engineWadingPremium * 0.15  # 涉水险不计免赔
                    MarkPremium['engineWadingMarkPremium'] = round(engineWadingMarkPremium, 2)

                elif num == 1:
                    compulsory_insurance = float(k["attributeVoList"]["Cvrg.NBefPrm"]["value"]) * jq_ratio  # 交强险
                    # log.info(str(compulsory_insurance) + u' 交强险')
                    Premium['compulsory_insurance'] = round(compulsory_insurance, 2)

                Premium['NAggTax'] = round(VsTax_NAggTax, 2)

            log.info(u'应缴保费总额 - {0}'.format(total_money))

            BaoE = {}

            _driverDutyPremium = insuranceType.get("driverDutyPremium", None)
            _carDamagePremium = insuranceType.get("carDamagePremium", "0")
            _otherHurtPremium = insuranceType.get("otherHurtPremium", None)
            _passengerDutyPremium = insuranceType.get("passengerDutyPremium", None)
            _carTheftPremium = insuranceType.get("carTheftPremium", "0")
            _carFireBrokenBenchMarkPremium = insuranceType.get("carFirePremium", "0")
            _engineWadingBenchMarkPremium = insuranceType.get("engineWadingPremium", "0")
            _carNickPremium = insuranceType.get("carNickPremium", None)  # 划痕险

            Vhl_NNewPurchaseValue = car_info.get('Vhl_NNewPurchaseValue', 0)
            seats = car_info.get('seats', 5)

            otherHurtBaoE = float(_otherHurtPremium.get("Amount")) if _otherHurtPremium and int(
                _otherHurtPremium.get("isCheck"), 0) and int(_otherHurtPremium.get("Amount"), 0) else None  # 三者险保额
            if otherHurtBaoE:
                BaoE['otherHurtBaoE'] = round(otherHurtBaoE, 2)

            carDamageBaoE = float(Vhl_NNewPurchaseValue) if int(_carDamagePremium) else None  # 车损险保额
            if carDamageBaoE:
                BaoE['carDamageBaoE'] = round(carDamageBaoE, 2)

            driverDutyBaoE = float(_driverDutyPremium.get("Amount")) if _driverDutyPremium and int(
                _driverDutyPremium.get("isCheck"), 0) and int(_driverDutyPremium.get("Amount"), 0) else None  # 驾驶人责任险
            if driverDutyBaoE:
                BaoE['driverDutyBaoE'] = round(driverDutyBaoE, 2)

            passengerDutyBaoE = float(_passengerDutyPremium.get("Amount")) * (
                seats - 1) if _passengerDutyPremium and int(_passengerDutyPremium.get("isCheck"), 0) and int(
                _passengerDutyPremium.get("Amount"), 0) else None  # 乘客责任险
            if passengerDutyBaoE:
                BaoE['passengerDutyBaoe'] = round(passengerDutyBaoE, 2)

            carTheftBaoE = float(Vhl_NNewPurchaseValue) if int(_carTheftPremium) else None  # 车盗险保额
            if carTheftBaoE:
                BaoE['carTheftBaoE'] = round(carTheftBaoE, 2)

            carNickBaoE = float(_carNickPremium.get("Amount")) if _carNickPremium and int(
                _carNickPremium.get("isCheck"),
                0) and int(
                _carNickPremium.get("Amount"), 0) else None  # 划痕险保额
            if carNickBaoE:
                BaoE['carNickBaoE'] = round(carNickBaoE, 2)

            engineWadingBaoE = float(Vhl_NNewPurchaseValue) if int(_engineWadingBenchMarkPremium) else None  # 涉水险保额
            if engineWadingBaoE:
                BaoE['engineWadingBaoE'] = round(engineWadingBaoE, 2)

            carFireBaoE = float(Vhl_NNewPurchaseValue) if int(_carFireBrokenBenchMarkPremium) else None  # 自燃险保额
            if carFireBaoE:
                BaoE['carFireBaoE'] = round(carFireBaoE, 2)

            disCount = {
                "sy_disCount": ratio,
                "jq_disCount": jq_ratio
            }

            PremiumInfo = [Premium, BaoE, MarkPremium, disCount]

            log.info(PremiumInfo)

            soupDb(PremiumInfo,
                   [utils.getlatedate(1) + ' 00:00:00', utils.getlatedate(365) + " 23:59:59", seats,
                    insuranceTypeGroupId,
                    insureCarId, "12"])

            send_mq(client, CPlateNo, "", "1", "12", sessionId, isPhone, insuranceTypeGroupId, insuranceTypeGroup)
            log.info(u"安城入库成功:%s|%s" % (CPlateNo, searchVin))

        return

    except Exception as e:
        log.error(traceback.format_exc())
        send_mq(client, CPlateNo, "未知异常", "2", "12", sessionId, isPhone, insuranceTypeGroupId, insuranceTypeGroup)
        return 0


if __name__ == "__main__":
    data1 = {'insureCarId': 3797, 'firstRegister': u'', 'cityCode': '32010000', 'vinNo': u'LVSHDFAC4DN574258',
             'plateNumber': u'苏AH19M3', 'vehicleBrand': u'',
             'custName': u'\u9648\u7fe0\u7ea2', 'insuranceType': {u'carDamageBenchMarkPremium': u'1',  # 车损险不计免赔
                                                                  u'carDamagePremium': u'1',  # 车损险

                                                                  u'driverDutyPremium': {u'Amount': u'10000',
                                                                                         u'isCheck': u'1'},  # 车上人员险（司机）
                                                                  u'driverDutyBenchMarkPremium': u'1',  # 车上人员险（司机）不计免赔

                                                                  u'passengerDutyPremium': {u'Amount': u'10000',
                                                                                            u'isCheck': u'1'},
                                                                  # 车上人员险（乘客）
                                                                  u'passengerBenchMarkPremium': u'1',  # 车上人员险（乘客）不计免赔

                                                                  u'carFirePremium': u'1',  # 自燃险
                                                                  u'carFireBrokenBenchMarkPremium': u'1',  # 自燃险不计免赔

                                                                  u'carTheftPremium': u'1',  # 盗抢险
                                                                  u'carTheftBenchMarkPremium': u'1',  # 盗抢险不计免赔

                                                                  u'otherHurtPremium': {u'Amount': u'500000',
                                                                                        u'isCheck': u'1'},  # 三者险
                                                                  u'otherHurtBenchMarkPremium': u'1',  # 三者险不计免赔

                                                                  u'engineWadingPremium': u'1',  # 涉水险
                                                                  u'engineWadingBenchMarkPremium': u'1',  # 涉水险不计免赔

                                                                  u'carNickPremium': {u'Amount': u'2000',
                                                                                      u'isCheck': u'1'},  # 划痕险
                                                                  u'carNickBenchMarkPremium': u'1',  # 划痕险不计免赔

                                                                  u'nAggTax': u'1',

                                                                  u'insuranceTypeGroupId': u'183',

                                                                  u'glassBrokenPremium': u'1',  # 玻璃破碎险
                                                                  u'compulsoryInsurance': u'1',
                                                                  u'insuranceTypeGroup': u'1_11_110_12_2_20_3_30_4_5_50_6_8_20000_80_9'},
             'sessionId': u'2bbcd99cd95d9b8fdf98b29e163686f6bca30736', 'engineNo': u'0651004', 'NSeatNum': u'5',
             'identitCard': u'320121197607280023', 'endDate': u'2017-04-7', 'isPhone': u'1'}

    data2 = {'insureCarId': 3797, 'firstRegister': u'', 'cityCode': '32010000', 'vinNo': u'WP1AA2957FLB19486',
             'plateNumber': u'苏H02C90', 'vehicleBrand': u'',
             'custName': u'\u9648\u7fe0\u7ea2', 'insuranceType': {u'carDamageBenchMarkPremium': u'1',  # 车损险不计免赔
                                                                  u'carDamagePremium': u'1',  # 车损险

                                                                  u'driverDutyPremium': {u'Amount': u'10000',
                                                                                         u'isCheck': u'0'},
                                                                  # 车上人员险（司机）
                                                                  u'driverDutyBenchMarkPremium': u'0',
                                                                  # 车上人员险（司机）不计免赔

                                                                  u'passengerDutyPremium': {u'Amount': u'10000',
                                                                                            u'isCheck': u'0'},
                                                                  # 车上人员险（乘客）
                                                                  u'passengerBenchMarkPremium': u'0',
                                                                  # 车上人员险（乘客）不计免赔

                                                                  u'carFirePremium': u'0',  # 自燃险
                                                                  u'carFireBrokenBenchMarkPremium': u'0',  # 自燃险不计免赔

                                                                  u'carTheftPremium': u'0',  # 盗抢险
                                                                  u'carTheftBenchMarkPremium': u'0',  # 盗抢险不计免赔

                                                                  u'otherHurtPremium': {u'Amount': u'500000',
                                                                                        u'isCheck': u'0'},  # 三者险
                                                                  u'otherHurtBenchMarkPremium': u'0',  # 三者险不计免赔

                                                                  u'engineWadingPremium': u'0',  # 涉水险
                                                                  u'engineWadingBenchMarkPremium': u'0',  # 涉水险不计免赔

                                                                  u'carNickPremium': {u'Amount': u'2000',
                                                                                      u'isCheck': u'0'},  # 划痕险
                                                                  u'carNickBenchMarkPremium': u'0',  # 划痕险不计免赔

                                                                  u'nAggTax': u'1',

                                                                  u'insuranceTypeGroupId': u'183',

                                                                  u'glassBrokenPremium': u'0',  # 玻璃破碎险
                                                                  u'compulsoryInsurance': u'1',
                                                                  u'insuranceTypeGroup': u'1_11_110_12_2_20_3_30_4_5_50_6_8_20000_80_9'},
             'sessionId': u'2bbcd99cd95d9b8fdf98b29e163686f6bca30736', 'engineNo': u'0651004', 'NSeatNum': u'5',
             'identitCard': u'320121197607280023', 'endDate': u'2017-04-7', 'isPhone': u'1'}

    data3 = {'insureCarId': 3797, 'firstRegister': u'', 'cityCode': '32010000', 'vinNo': u'WP1AA2957FLB19486',
             'plateNumber': u'苏H02C90', 'vehicleBrand': u'',
             'custName': u'\u9648\u7fe0\u7ea2', 'insuranceType': {u'carDamageBenchMarkPremium': u'1',  # 车损险不计免赔
                                                                  u'carDamagePremium': u'1',  # 车损险

                                                                  u'driverDutyPremium': {u'Amount': u'10000',
                                                                                         u'isCheck': u'0'},
                                                                  # 车上人员险（司机）
                                                                  u'driverDutyBenchMarkPremium': u'0',
                                                                  # 车上人员险（司机）不计免赔

                                                                  u'passengerDutyPremium': {u'Amount': u'10000',
                                                                                            u'isCheck': u'0'},
                                                                  # 车上人员险（乘客）
                                                                  u'passengerBenchMarkPremium': u'0',
                                                                  # 车上人员险（乘客）不计免赔

                                                                  u'carFirePremium': u'1',  # 自燃险
                                                                  u'carFireBrokenBenchMarkPremium': u'1',  # 自燃险不计免赔

                                                                  u'carTheftPremium': u'1',  # 盗抢险
                                                                  u'carTheftBenchMarkPremium': u'1',  # 盗抢险不计免赔

                                                                  u'otherHurtPremium': {u'Amount': u'500000',
                                                                                        u'isCheck': u'0'},  # 三者险
                                                                  u'otherHurtBenchMarkPremium': u'0',  # 三者险不计免赔

                                                                  u'engineWadingPremium': u'0',  # 涉水险
                                                                  u'engineWadingBenchMarkPremium': u'0',  # 涉水险不计免赔

                                                                  u'carNickPremium': {u'Amount': u'2000',
                                                                                      u'isCheck': u'0'},  # 划痕险
                                                                  u'carNickBenchMarkPremium': u'0',  # 划痕险不计免赔

                                                                  u'nAggTax': u'1',

                                                                  u'insuranceTypeGroupId': u'183',

                                                                  u'glassBrokenPremium': u'0',  # 玻璃破碎险
                                                                  u'compulsoryInsurance': u'1',
                                                                  u'insuranceTypeGroup': u'1_11_110_12_2_20_3_30_4_5_50_6_8_20000_80_9'},
             'sessionId': u'2bbcd99cd95d9b8fdf98b29e163686f6bca30736', 'engineNo': u'0651004', 'NSeatNum': u'5',
             'identitCard': u'320121197607280023', 'endDate': u'2017-04-7', 'isPhone': u'1'}

    data4 = {'insureCarId': 3797, 'firstRegister': u'', 'cityCode': '32010000', 'vinNo': u'LSVCT6A42EN077467',
             'plateNumber': u'苏AQ193V', 'vehicleBrand': u'',
             'custName': u'\u9648\u7fe0\u7ea2', 'insuranceType': {u'carDamageBenchMarkPremium': u'1',  # 车损险不计免赔
                                                                  u'carDamagePremium': u'01',  # 车损险

                                                                  u'driverDutyPremium': {u'Amount': u'',
                                                                                         u'isCheck': u'0'},
                                                                  # 车上人员险（司机）
                                                                  u'driverDutyBenchMarkPremium': u'0',
                                                                  # 车上人员险（司机）不计免赔

                                                                  u'passengerDutyPremium': {u'Amount': u'',
                                                                                            u'isCheck': u'0'},
                                                                  # 车上人员险（乘客）
                                                                  u'passengerBenchMarkPremium': u'0',
                                                                  # 车上人员险（乘客）不计免赔

                                                                  u'carFirePremium': u'0',  # 自燃险
                                                                  u'carFireBrokenBenchMarkPremium': u'0',
                                                                  # 自燃险不计免赔

                                                                  u'carTheftPremium': u'0',  # 盗抢险
                                                                  u'carTheftBenchMarkPremium': u'0',  # 盗抢险不计免赔

                                                                  u'otherHurtPremium': {u'Amount': u'',
                                                                                        u'isCheck': u'0'},  # 三者险
                                                                  u'otherHurtBenchMarkPremium': u'0',  # 三者险不计免赔

                                                                  u'engineWadingPremium': u'0',  # 涉水险
                                                                  u'engineWadingBenchMarkPremium': u'0',
                                                                  # 涉水险不计免赔

                                                                  u'carNickPremium': {u'Amount': u'',
                                                                                      u'isCheck': u'0'},  # 划痕险
                                                                  u'carNickBenchMarkPremium': u'0',  # 划痕险不计免赔

                                                                  u'nAggTax': u'1',

                                                                  u'insuranceTypeGroupId': u'183',

                                                                  u'glassBrokenPremium': u'0',  # 玻璃破碎险
                                                                  u'compulsoryInsurance': u'1',
                                                                  u'insuranceTypeGroup': u'1_11_110_12_2_20_3_30_4_5_50_6_8_20000_80_9'},
             'sessionId': u'2bbcd99cd95d9b8fdf98b29e163686f6bca30736', 'engineNo': u'0651004', 'NSeatNum': u'5',
             'identitCard': u'320121197607280023', 'endDate': u'2017-04-7', 'isPhone': u'1'}

    datas = [data1]
    for data in datas:
        # 获取session
        r = CRedis()
        sessBase = r.get('12_COMPANY')
        if not sessBase:
            session = login_ancheng()
        else:
            session = pickle.loads(codecs.decode(sessBase.encode(), "base64"))

        get_premium(session, data)
